package controllers

import javax.inject.Inject

import play.api.mvc._
import dao._
import models.Tables._
import play.api.libs.json.Json
import play.api.data.Form
import play.api.data.Forms._

import scala.concurrent.ExecutionContext.Implicits.global

case class RegionData(chr: String, start: Int, end: Int)


class GenomeSearchController @Inject()(cc:ControllerComponents,bgAnnoDao: BgAnnoDao) extends AbstractController(cc) {

  case class GeneIdData(geneId: String)


  val geneIdForm = Form(
    mapping(
      "geneId" -> text
    )(GeneIdData.apply)(GeneIdData.unapply)
  )

  val regionForm = Form(
    mapping(
      "chr" -> text,
      "start" -> number,
      "end" -> number
    )(RegionData.apply)(RegionData.unapply)
  )

  def searchByGeneIdBefore = Action {
    Ok(views.html.genome.search.searchByGeneId())
  }

  def searchByRegionBefore = Action {
    Ok(views.html.genome.search.searchByRegion())
  }

  def getAllGeneIds = Action.async {
    bgAnnoDao.selectAllGeneIds.map { x =>
      Ok(Json.toJson(x))
    }
  }

  def getAllChrs = Action.async {
    bgAnnoDao.selectAllChrs.map { x =>
      Ok(Json.toJson(x))
    }
  }

  def searchByGeneId = Action.async { implicit request =>
    val data = geneIdForm.bindFromRequest.get
    val geneIds = data.geneId.split(",").distinct
    bgAnnoDao.selectByGeneIds(geneIds).map { x =>
      val array = getArrayByBgAnnos(x)
      Ok(Json.toJson(array))
    }
  }

  def searchByRegion = Action.async { implicit request =>
    val data = regionForm.bindFromRequest.get
    bgAnnoDao.selectByRegionData(data).map { x =>
      val array = getArrayByBgAnnos(x)
      Ok(Json.toJson(array))
    }
  }

  def getArrayByBgAnnos(x: Seq[BgannoRow]) = {
    x.map { y =>
      val geneIdStr = "<a target='_blank' title='more' href='" + routes.GenomeBrowseController.getDetailInfo(y.geneid) + "'>" + y.geneid + "</a>"
      Json.obj(
        "geneId" -> geneIdStr, "chr" -> y.chr, "start" -> y.start, "end" -> y.end, "dir" -> y.dir, "kegg" -> y.kegg,
        "ipr" -> y.ipr, "interPro" -> y.interpro, "goPlant" -> y.goplant, "keggPlant" -> y.keggplant, "nrId" -> y.nrid
      )
    }
  }


}
